package com.kfm.wiki.controller;

import cn.hutool.core.util.IdUtil;
import com.kfm.wiki.entity.User;
import com.kfm.wiki.service.UserService;
import com.kfm.wiki.util.Contains;
import com.kfm.wiki.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/login")
    public R login(@RequestBody User user){
        User loginUser = userService.login(user);
        // 将密码清空
        loginUser.setPassword(null);

        // 创建一个 token
        loginUser.setToken(String.valueOf(IdUtil.getSnowflakeNextId()));

        // 将用户信息存到 redis 中 ， kye: user_12378g3ibsdf78  value: user
        redisTemplate.opsForValue().set(Contains.REDIS_LOGIN_KEY_PRE + loginUser.getToken(), loginUser, 4, TimeUnit.HOURS);
        return R.ok(loginUser);
    }

    @GetMapping("/logout")
    public R logout(@RequestHeader(value = "token") String token){
        // 从 redis 中删除对应的用户信息
        redisTemplate.delete(Contains.REDIS_LOGIN_KEY_PRE + token);
        return R.ok();
    }
}
